//路由配置
import {createRouter, createWebHistory} from "vue-router";

import NProgress from 'nprogress';

import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })
//定义路由信息
const routes = [{
    path: "/login",
    name: "login",
    component: () => import("../pages/Login.vue")
}, {
    path: "/index",
    name: "index",
    redirect: '/index/welcome',
    component: () => import("../pages/Index.vue"),
    children: [{
        path: "welcome",
        name: "welcome",
        component: () => import("../pages/welcome.vue"),
    },{
        path: "/userlist",
        name: "userlist",
        component: () => import("../pages/User/Userlist.vue"),
    },{
        path: "/useradd",
        name: "useradd",
        component: () => import("../pages/User/useradd.vue"),
    },{
        path: "payList",
        name: "payList",
        component: () => import("../pages/pay/PayList.vue"),
    }]
}, {
    path: "/",
    redirect: "/index"
}];

//定义路由对象
const router = createRouter({
    history: createWebHistory(),
    routes
});
//配置路由的全局前置导航守卫
router.beforeEach((to, from, next) => {
    console.log("前置");
    //开启滚动条
    NProgress.start();
    //访问的非登录组件以外的组件，需要判断sessionStorage中有token
    let token = sessionStorage.getItem("token");
    if (to.name == 'login'){
        //跳转的是登录组件，可以直接跳转
        next();
    }else {
        if (!token){
            //没有登录
            next({
               name: 'login'
            });
        }else {
            //登录
            next();
        }
    }
});
//配置路由的全局后置钩子
router.afterEach((to, from) => {
    console.log("后置");
    //关闭滚动条
    NProgress.done();
});
//对外暴露模块
export default router;